package com.ma.chapter8.executors;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName TestSubmit
 * @Author: mayongqiang
 * @DATE 2022/3/21 22:50
 * @Description: 线程池 submit(Callable task)提交任务
 */
@Slf4j(topic = "m.TestSubmit")
public class TestSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        String res = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin 11");
                    Thread.sleep(1000);
                    log.debug("end 11");
                    return "1";
                },
                () -> {
                    log.debug("begin  22");
                    Thread.sleep(500);
                    log.debug("end 22");
                    return "2";
                },
                () -> {
                    log.debug("begin  33");
                    Thread.sleep(2000);
                    log.debug("end 33");
                    return "3";
                }
        ));
        System.out.println(res);

    }

    private static void method2(ExecutorService pool) throws InterruptedException {
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    return "1";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(500);
                    return "2";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    return "3";
                }
        ));
        futures.forEach(f->{
            try {
                log.debug(f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    private static void method1(ExecutorService pool) throws InterruptedException, ExecutionException {
        Future<String> future = pool.submit(() -> {
            log.debug("running");
            Thread.sleep(1000);
            return "ok";
        });
        log.debug("{}", future.get());
    }
}
